package top.azusall.securitydemo.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import top.azusall.common.entity.R;
import top.azusall.model.dto.LoginDTO;
import top.azusall.securitydemo.common.MyUserDetail;
import top.azusall.securitydemo.service.UserService;
import top.azusall.securitydemo.thread.UserDetailThreadLocalUtil;
import top.azusall.securitydemo.util.JwtUtil;

/**
 * @author houmo
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private final AuthenticationManager authenticationManager;

    public UserServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }


    @Override
    public R login(String username, String password) {
        log.info("开始登录 username: {}, password: {}", username, password);
        // 实现登录后，可以正常访问其他接口
        UsernamePasswordAuthenticationToken unauthenticated = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
        log.info("开始authenticate");
        Authentication authenticate = this.authenticationManager.authenticate(unauthenticated);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        MyUserDetail details = UserDetailThreadLocalUtil.get();

        // 生成JWT
        String token = JwtUtil.generateJwt(details);
        LoginDTO loginDTO = new LoginDTO();
        loginDTO.setToken(token);
        loginDTO.setUser(details.getUser());

        return R.ok("", loginDTO);
    }
}
